//
//  SEAllergyHistoryHeader.swift
//  SmartEyeForPatient
//
//  Created by QDSG on 2021/4/6.
//

import UIKit

class SEAllergyHistoryHeader: UIView {
    
    private var valueChanged: ((SEInquiryInfoViewModel) -> Void)?
    
    private var viewModel: SEInquiryInfoViewModel?
    
    func update(with viewModel: SEInquiryInfoViewModel, valueChanged: ((SEInquiryInfoViewModel) -> Void)?) {
        self.viewModel = viewModel
        self.valueChanged = valueChanged
        segmentedControl.selectedSegmentIndex = viewModel.hasAllergyHistory ? 0 : 1
    }
    
    @IBAction func segmentChangeAction(_ sender: UISegmentedControl) {
        guard let viewModel = viewModel else { return }
        var has = viewModel.hasAllergyHistory
        if has {
            sender.selectedSegmentIndex = 1
            has = false
        } else {
            sender.selectedSegmentIndex = 0
            has = true
        }
        viewModel.hasAllergyHistory = has
        valueChanged?(viewModel)
    }
    
    @IBOutlet private weak var segmentedControl: UISegmentedControl! {
        didSet {
            segmentedControl.setSegmentedStyle(normalColor: UIColor.white,
                                               selectedColor: UIColor(hex: "#4AD4AC"),
                                               dividerColor: UIColor(hex: "#4AD4AC"))
        }
    }

}

extension UISegmentedControl {
    /// 自定义 segmentedControl 样式
    /// - Parameters:
    ///   - normalColor:   普通状态下的背景色
    ///   - selectedColor: 选中状态下的背景色
    ///   - normalTitleColor:   普通状态下的文字颜色
    ///   - selectedTitleColor: 选中状态下的文字颜色
    ///   - dividerColor:  分割线颜色
    func setSegmentedStyle(normalColor: UIColor, selectedColor: UIColor, normalTitleColor: UIColor = UIColor(hex: "#C8C8C8"), selectedTitleColor: UIColor = UIColor.white, dividerColor: UIColor) {
        setBackgroundImage(normalColor.image(), for: .normal, barMetrics: .default)
        setBackgroundImage(selectedColor.image(), for: .selected, barMetrics: .default)
        setDividerImage(dividerColor.image(), forLeftSegmentState: .normal, rightSegmentState: .normal, barMetrics: .default)
        
        let normalAttributes = [
            NSAttributedString.Key.foregroundColor: normalTitleColor,
            NSAttributedString.Key.font: UIFont.regular(14)
        ]
        setTitleTextAttributes(normalAttributes, for: .normal)
        
        let selectedAttributes = [
            NSAttributedString.Key.foregroundColor: selectedTitleColor,
            NSAttributedString.Key.font: UIFont.medium(14)
        ]
        setTitleTextAttributes(selectedAttributes, for: .selected)
        
        layer.cornerRadius = 2.0
        layer.borderWidth = 1
        layer.borderColor = dividerColor.cgColor
        layer.masksToBounds = true
    }
}
